package com.paipaideli.ui.mine.head;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.jakewharton.rxbinding2.view.RxView;
import com.paipaideli.MyApplication;
import com.paipaideli.R;
import com.paipaideli.alipay.PayResult;
import com.paipaideli.common.base.BasePresenterActivity;
import com.paipaideli.common.http.Api;
import com.paipaideli.common.pullrefresh.PullRefreshView;
import com.paipaideli.common.utils.DateUtil;
import com.paipaideli.common.utils.ToastUtil;
import com.paipaideli.common.utils.preferrnces.FastData;
import com.paipaideli.common.views.CommonDialogView;
import com.paipaideli.ui.MainActivity;
import com.paipaideli.ui.mine.head.bean.AssetsBean;
import com.paipaideli.ui.mine.safety.event.LogoutEvent;
import com.paipaideli.ui.price.PriceActivity;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * Created by 我的资产
 */
public class AssetsActivity extends BasePresenterActivity {

    Unbinder unbinder;
    @BindView(R.id.top_back)
    RelativeLayout top_back;
    @BindView(R.id.top_title)
    TextView top_title;
    @BindView(R.id.tv_assets_kqye)
    TextView tvAssetsKqye;
    @BindView(R.id.tv_assets_zhze)
    TextView tvAssetsZhze;
    @BindView(R.id.tv_assets_djje)
    TextView tvAssetsDjje;
    @BindView(R.id.tv_assets_gz)
    TextView tv_assets_gz;
    @BindView(R.id.lin_assets_tx)
    LinearLayout linAssetsTx;
    @BindView(R.id.lin_assets_cpzg)
    LinearLayout linAssetsCpzg;
    @BindView(R.id.recycleview_assets)
    PullRefreshView recycleview_assets;
    @BindView(R.id.imageView39)
    ImageView imageView39;
    @BindView(R.id.imageView40)
    ImageView imageView40;

    private AssetsAdapter assetsAdapter;
    private List<AssetsBean.Data.TradeRecordRes> list = new ArrayList<>();
    private int curPage = 1;
    private int total;
    private String isName;
    private double ye;
    private int pageSize;

    private static final int SDK_PAY_FLAG = 1;
    private String outTradeNo;
    private String authFreeze;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        AlipayQuery();//支付宝回调查询
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(AssetsActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        } else if (TextUtils.equals(resultStatus, "6001")) {
                            Toast.makeText(AssetsActivity.this, "支付取消", Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(AssetsActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    public int getContentView() {
        return R.layout.activity_assets;
    }

    @Override
    public void initView() {
        unbinder = ButterKnife.bind(this);
        top_title.setText("我的资产");
        isName = getIntent().getStringExtra("certificationStatu");

        //返回
        top_back.setOnClickListener(o ->
                showBroud()
        );

        imageView39.setOnClickListener(e -> {
            showMyDialog("可取金额=账户总额-冻结金额");
        });
        imageView40.setOnClickListener(e -> {
            showMyDialog("冻结金额是指：有拍中未付款的商品或者有正在参加的拍场");
        });

        recycleview_assets.setEnableRefresh(true);
        recycleview_assets.setEnableLoadmore(true);
        //设置是否在全部加载结束之后Footer跟随内容
        recycleview_assets.setOnRefreshListener(refreshlayout -> {
            curPage = 1;
            initData();
            recycleview_assets.finishRefresh();
        });

        recycleview_assets.setLoadmoreListener(refreshlayout -> {
            double p = Math.ceil(Double.valueOf(total) / Double.valueOf(pageSize));
            int page = Integer.valueOf((int) p);
            if (curPage < page) {
                curPage++;
                initData();
            } else {
                //加载完成 并且 标记为没有更多数据
                refreshlayout.finishLoadmoreWithNoMoreData();
            }
            recycleview_assets.finishLoadmore();
        });
        assetsAdapter = new AssetsAdapter();
        recycleview_assets.setLayoutManager(new LinearLayoutManager(this));
        recycleview_assets.setAdapter(assetsAdapter);

        //提现操作
        RxView.clicks(linAssetsTx)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(o -> {
            if (isName.equals("1")) {
                Intent intent = new Intent(AssetsActivity.this, CashActivity.class);
                intent.putExtra("price", ye);
                startActivity(intent);
            } else {
                ToastUtil.show("您尚未实名，请先进行实名操作！");
            }
        }, throwable -> {
        });

        //获取参拍资格
        RxView.clicks(linAssetsCpzg).subscribe(o -> {
            if (authFreeze.equals("0")) {
                intozfb();
            } else {
                unFreeze();
            }
        }, throwable -> {
        });
    }

    private void showBroud() {
        finish();
        LogoutEvent logoutEvent = new LogoutEvent();
        logoutEvent.setCheck(4);
        EventBus.getDefault().post(logoutEvent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        list.clear();
        recycleview_assets.showLoading();
        //初始化数据
        initData();
    }

    private void showMyDialog(String msg) {
        final CommonDialogView dialog = new CommonDialogView(AssetsActivity.this);
        dialog.setMessage(msg)
                .setTitle("温馨提示")
                .setPositive("朕知道了")
                .setSingle(true).setOnClickBottomListener(new CommonDialogView.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                dialog.dismiss();

            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();

            }
        }).show();

//        Dialog dialog = new Dialog(this);
//        dialog.setCanceledOnTouchOutside(false);//点击空白区域不消失
//        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        dialog.setContentView(R.layout.layout_dialog_twobtn);
//        Window dialogWindow = dialog.getWindow();
//        dialogWindow.setGravity(Gravity.CENTER);
//        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//        lp.width = WindowManager.LayoutParams.FILL_PARENT;
//        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
//        dialogWindow.setAttributes(lp);
//        dialog.show();
//
//        TextView tv_dialog_title=dialog.findViewById(R.id.tv_dialog_title);
//        tv_dialog_title.setText(msg);
//        Button dialog_btn_ok=dialog.findViewById(R.id.dialog_btn_ok);
//        dialog_btn_ok.setText("朕知道了");
//
//        dialog.findViewById(R.id.dialog_btn_ok).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                dialog.dismiss();
//            }
//        });
    }

    private void initData() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("curPage", curPage);
            requestData.put("pageSize", "10");
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().assets(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    if (request.code.equals("200")) {
                        authFreeze = request.data.authFreeze;
                        if (authFreeze.equals("0")) {
                            tv_assets_gz.setText("获取参拍资格");
                        } else {
                            tv_assets_gz.setText("解除预授资格");
                        }
                        ye = Double.valueOf(request.data.remainder) - Double.valueOf(request.data.earnestMoney);
                        tvAssetsKqye.setText(String.format("%.2f", ye) + "");
                        tvAssetsZhze.setText(request.data.remainder);
                        tvAssetsDjje.setText(request.data.earnestMoney);
                        list = request.data.tradeRecordRes;
                        total = request.total;
                        curPage = request.curPage;
                        pageSize = request.pageSize;
                        assetsAdapter.notifyDataSetChanged();
                        recycleview_assets.finishLoading();
                        ToastUtil.show(request.msg);
                    } else {
                        recycleview_assets.showEmpty(request.msg);
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    Log.e(TAG, "error", throwable);
                });
    }

    private void intozfb() {
        final CommonDialogView dialog = new CommonDialogView(AssetsActivity.this);
        dialog.setMessage("您尚未有参拍资格，请去充值押金（300元）或者开通支付宝预授权获得参拍资格")
                .setTitle("温馨提示")
                .setPositive("支付宝授权")
                .setNegtive("去充值")
                .setSingle(false).setOnClickBottomListener(new CommonDialogView.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                dialog.dismiss();
                auth();
            }

            @Override
            public void onNegtiveClick() {
                dialog.dismiss();
                MyApplication.isAlipay = 0;
                Intent intent = new Intent(AssetsActivity.this, InvestActivity.class);
                startActivity(intent);
            }
        }).show();

//        Dialog dialog = new Dialog(this);
//        dialog.setCanceledOnTouchOutside(true);//点击空白区域不消失
//        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        dialog.setContentView(R.layout.layout_dialog_assets);
//        Window dialogWindow = dialog.getWindow();
//        dialogWindow.setGravity(Gravity.CENTER);
//        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//        lp.width = WindowManager.LayoutParams.FILL_PARENT;
//        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
//        dialogWindow.setAttributes(lp);
//        dialog.show();
//        Button button1 = dialog.findViewById(R.id.dialog_btn_no);
//        //button1.setText("支付宝授权");
//        Button button2 = dialog.findViewById(R.id.dialog_btn_ok);
//        //button2.setText("去充值");
//
//        addDisposable(RxView.clicks(button1)
//                .throttleFirst(1, TimeUnit.SECONDS)
//                .subscribe(o -> {
//                    dialog.dismiss();
//                    auth();
//                }));
//
//        addDisposable(RxView.clicks(button2)
//                .throttleFirst(1, TimeUnit.SECONDS)
//                .subscribe(o -> {
//                    dialog.dismiss();
//                    Intent intent = new Intent(AssetsActivity.this, InvestActivity.class);
//                    startActivity(intent);
//                }));
    }

    public class AssetsAdapter extends RecyclerView.Adapter {

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(AssetsActivity.this).inflate(R.layout.item_profit_view, null);
            inflate.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            return new ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            ViewHolder viewHolder = (ViewHolder) holder;
            viewHolder.textPriceName.setText(list.get(position).tradeTitle);
            viewHolder.textPriceTime.setText(DateUtil.getDateToString(list.get(position).createTime));
            viewHolder.textPriceMoney.setText(list.get(position).totalFee + "");
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.text_price_name)
            TextView textPriceName;
            @BindView(R.id.text_price_time)
            TextView textPriceTime;
            @BindView(R.id.text_price_money)
            TextView textPriceMoney;

            public ViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    /**
     * 支付宝预授权
     */
    private void auth() {
        recycleview_assets.showLoading();
        JSONObject requestData = new JSONObject();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().free(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    recycleview_assets.finishLoading();
                    if (request.code.equals("200")) {
                        final String alipayInfo = request.data.body;
                        outTradeNo = request.data.outOrderNo;
                        FastData.setOutTradeNo(outTradeNo);
                        Runnable payRunnable = new Runnable() {
                            @Override
                            public void run() {
                                // 构造PayTask 对象
                                PayTask alipay = new PayTask(AssetsActivity.this);
                                // 调用支付接口，获取支付结果
                                String result = alipay.pay(alipayInfo, true);
                                Message msg = new Message();
                                msg.what = SDK_PAY_FLAG;
                                msg.obj = result;
                                mHandler.sendMessage(msg);
                            }
                        };
                        // 必须异步调用
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    } else {
                        ToastUtil.show(request.msg);
                    }
                }, throwable -> {
                    recycleview_assets.finishLoading();
                    Log.e(TAG, "error", throwable);
                });
    }


    private void AlipayQuery() {
        JSONObject requestData = new JSONObject();
        try {
            requestData.put("outOrderNo", FastData.getOutTradeNo());
        } catch (Exception e) {
            e.getMessage();
        }
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().freeQuery(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                }, throwable -> {
                    Log.e(TAG, "error", throwable);
                });

        MainActivity.openSingleTop(AssetsActivity.this);
    }

    //解除支付宝预授权
    private void unFreeze() {
        recycleview_assets.showLoading();
        JSONObject requestData = new JSONObject();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestData.toString());
        Api.getInstanceGson().unFreeze(body)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(request -> {
                    recycleview_assets.finishLoading();
                    if (request.getCode().equals("200")) {
                        list.clear();
                        recycleview_assets.showLoading();
                        //初始化数据
                        initData();
                        ToastUtil.show(request.getMessage());
                    } else {
                        ToastUtil.show(request.getMessage());
                    }
                }, throwable -> {
                    recycleview_assets.finishLoading();
                    Log.e(TAG, "error", throwable);
                });
    }

}
